webkit内核不支持WebSocket 401响应

使用 chrome 浏览器连接 WebSocket 服务时权限验证失败,ws 连接一直处于 pending 状态。
由于使用了 npm ws 包处理 WebSocket 连接,因此去看源代码有下面一段,ws 默认会返回 401 状态码,由于代码中 verifyClient 回调没有传入 code 参数,因此默认返回了 401,
于是乎修改 code 状态码为 400、402、403、404 进行测试均可顺利断开连接,唯有 401 有问题,换 Firefox 浏览器返回 401 是可以处理的,由此推断是 401 导致的问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//
// Optionally call external client verification handler.
//
if (this.options.verifyClient) {
const info = {
origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
secure: !!(req.connection.authorized || req.connection.encrypted),
req
};

if (this.options.verifyClient.length === 2) {
this.options.verifyClient(info, (verified, code, message, headers) => {
if (!verified) {
return abortHandshake(socket, code || 401, message, headers);
}

this.completeUpgrade(extensions, req, socket, head, cb);
});
return;
}

if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
}

google 搜索 “websocket 401”,拿到下面的一个地址,明确说明 webkit 内核的一个 bug,对于 websocket 连接来说,不支持 401 状态码,因此连接返回 401 会一直处于 pending 状态,也不会触发任何事件。
此 bug 2012 年已经存在,至今未进行修复。
查看 bug 详情

◀        
        ▶